package com.cskaoyan.jdbc.util;

import java.io.FileInputStream;
import java.io.IOException;
import java.sql.*;
import java.util.Properties;

/**
 * 创建日期: 2022/06/01 11:41
 *
 * @author ciggar
 */
public class JDBCUtils {

    static String url;
    static String username;
    static String password;
    static String driver;


    static {

        Properties properties = new Properties();
        try {
            properties.load(new FileInputStream("jdbc.properties"));
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 获取值
        url = properties.getProperty("url");
        username = properties.getProperty("username");
        password = properties.getProperty("password");
        driver = properties.getProperty("driver");
    }



    // 获取连接
    public static Connection getConnection(){

        Connection connection = null;

        // 1. 注册驱动  // 传入的是驱动包里面的Driver接口的实现
        try {
//            DriverManager.registerDriver(new Driver());
            Class.forName(driver);


        // 2. 建立连接 JDBC4Connection
            connection = DriverManager.getConnection(url,username,password);

        } catch (SQLException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return connection;
    }



    // 关闭资源 //指令重排序 ,如果禁止呢？ volatile
//    static {
//
//        int i = 1;
//        int m = 2;
//        int n = i+m;
//
//
//    }

    // 关闭资源
    public static void close(ResultSet resultSet, Statement statement,Connection connection){

        try {
            if (resultSet != null) resultSet.close();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                if (statement != null) statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            } finally {
                if (connection != null) {
                    try {
                        connection.close();
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}
